package com.wyz.note.project.security.config;

import com.wyz.note.project.security.pojo.Menu;
import com.wyz.note.project.security.pojo.Role;
import com.wyz.note.project.security.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.List;

/**
 * @Description: 自定义的Metadata，通过当前请求地址，获取该地址所需要的角色
 * @Author: wei yz
 * @Date: 2022/6/18 15:31
 */
@Component
public class NoteSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private static final Logger log = LoggerFactory.getLogger(NoteSecurityMetadataSource.class);

    /**
     * 菜单服务类
     */
    @Autowired
    private MenuService menuService;
    /**
     * 匹配规则
     */
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        // object 中包含用户请求的 request 信息
        HttpServletRequest request = ((FilterInvocation) object).getRequest();
        // 提取出当前的uri
        String requestURI = request.getRequestURI();
        log.info("当前登录的URI：{}", requestURI);
        // 查询所有的菜单信息
        List<Menu> allMenu = menuService.getAllMenu();
        log.info("查询的菜单信息：{}", allMenu);
        if (!CollectionUtils.isEmpty(allMenu)) {
            for (Menu menu : allMenu) {
                log.info("匹配菜单规则：{} <==> {}", menu.getPattern(), requestURI);
                // 匹配规则正确
                if (antPathMatcher.match(menu.getPattern(), requestURI)) {
                    if (CollectionUtils.isEmpty(menu.getRoles())) {
                        throw new IllegalArgumentException("该菜单未绑定角色信息：[ " + menu.getId() + " ]");
                    }
                    String[] roleCodes = menu.getRoles().stream().map(Role::getCode).toArray(String[]::new);
                    log.info("角色编码数组：{}", roleCodes);
                    return SecurityConfig.createList(roleCodes);
                }
            }
        }
        log.info("==> 菜单为空 <==");
        return null;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }
}
